package com.gskj.gulimall.seckill.interceptor;

import club.gskj.common.constant.AuthServerConstant;
import club.gskj.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserLoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRespVo> local = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MemberRespVo attribute = (MemberRespVo) request.getSession().getAttribute(AuthServerConstant.SESSION_LOGIN_USER);

        // 获取当前 请求uri
        String requestURI = request.getRequestURI();
        // 使用AntPathMatcher 字符串匹配，判断当前请求是否为指定请求路i，可放行的路径
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match1 = antPathMatcher.match("/kill", requestURI);
        if (!match1) {
            // 匹配直接放行，
            return true;
        }

        if (attribute != null) {
            // 用户已登录
            local.set(attribute);
            return true;
        }
        request.getSession().setAttribute("msg", "请先进行登陆");
        // 没有登陆，必须先登录用户信息
        response.sendRedirect("http://auth.gulimall.com/login.html");
        return false;
    }
}
